package com.example.Utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class ToPinyinUtil {
    public static String toPinyin(String chinese) {
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);

        for (char c : chinese.toCharArray()) {
            try {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                if (pinyinArray != null) {
                    // 将拼音首字母大写并添加到结果中
                    pinyin.append(Character.toUpperCase(pinyinArray[0].charAt(0)))
                            .append(pinyinArray[0].substring(1));
                } else {
                    // 如果不是汉字，则直接添加
                    pinyin.append(c);
                }
            } catch (Exception e) {
                e.printStackTrace();
                pinyin.append(c);
            }
        }

        return pinyin.toString();
    }

}
